import React, { Component } from 'react'

import {
  View,
  Text,
  Image,
  StyleSheet,
  Dimensions,
  ScrollView,
  TouchableWithoutFeedback
} from 'react-native'

const screenWidth = Dimensions.get('window').width
export default class BookInfo extends Component {
  constructor (props) {
    super(props)
    this.handleGoBack = this.handleGoBack.bind(this)
    this.handleClickStartRead = this.handleClickStartRead.bind(this)
    this.handleClickSort = this.handleClickSort.bind(this)
    this.state = {
      descpTab: [styles.bookInfoCTItem, styles.itemActive],
      catalogTab: [styles.bookInfoCTItem],
      cataLogsList: [],
      btnText: '倒序'
    }
  }
  
  
  handleClickStartRead(contentKey) {
    const key = contentKey || this.state.cataLogsList[0].contentKey
    const { navigation } = this.props
    const bookInfo = this.props.navigation.state.params
    navigation.navigate('Reader', { key: contentKey, book: bookInfo})
  }
  
  handleGoBack () {
    const { navigation } = this.props
    navigation.goBack()
  }

  handleClickSort () {
    const tmp = this.state.cataLogsList
    let text = this.state.btnText
    text = text === '正序' ? '倒序' : '正序'
    this.setState({
      cataLogsList: tmp.reverse(),
      btnText: text
    })
  }

  fetchCatalog (bookId) {
    return fetch(`https://p.du.163.com/book/catalog.json?bookId=${bookId}`)
      .then(res => {
        return res.json()
      })
      .catch(error => {
        console.error(error)
      })
  }

  componentDidMount () {
    const bookInfo = this.props.navigation.state.params
    this.fetchCatalog(bookInfo.strBookId)
      .then(res => {
        if (res && res.code === 0) {
          this.setState({
            cataLogsList: res.catalog
          })
        }
      })
  }
  
  render () {
    const bookInfo = this.props.navigation.state.params
    let _scrollView = null
    const { descpTab, catalogTab, cataLogsList, btnText } = this.state
    const self = this
    
    function tabChange(type) {
      if (type === 'catalog') {
        _scrollView.scrollTo({x: screenWidth, animated: true})
        self.setState({
          descpTab: [styles.bookInfoCTItem],
          catalogTab: [styles.bookInfoCTItem, styles.itemActive]
        })
      } else {
        _scrollView.scrollTo({x: 0, animated: true})
        self.setState({
          descpTab: [styles.bookInfoCTItem, styles.itemActive],
          catalogTab: [styles.bookInfoCTItem]
        })
      }
    }
    
    return (
      <View style={styles.bookInfo}>
        <TouchableWithoutFeedback onPress={this.handleGoBack}>
          <View style={styles.backButtonContainer}>
            <Text style={styles.backButton}>返回</Text>
          </View>
        </TouchableWithoutFeedback>
        <ScrollView>
          <View style={styles.bookInfoTitle}>
            <Image style={styles.bookCover} source={{uri: bookInfo.imageUrl}} />
            <View>
              <Text style={styles.bookTitle}>{bookInfo.title}</Text>
              <Text style={styles.bookAuthor}>{bookInfo.authors}</Text>
              <Text style={styles.readTime}>{bookInfo.readTimesTip}</Text>
            </View>
          </View>
          <View style={styles.bookInfoContent}>
            <View style={styles.bookInfoCTitle}>
              <TouchableWithoutFeedback onPress={ () => { tabChange('descp') } }>
                <View style={styles.bookInfoCTItemContainer}>
                  <Text style={descpTab}>详情</Text>
                </View>
              </TouchableWithoutFeedback>
              <TouchableWithoutFeedback onPress={ () => { tabChange('catalog') } }>
                <View style={styles.bookInfoCTItemContainer}>
                  <Text style={catalogTab}>目录</Text>
                </View>
              </TouchableWithoutFeedback>
            </View>
            <ScrollView
              horizontal={true}
              ref={(scrollView) => {_scrollView = scrollView}}
              style={{overflow: 'hidden'}}
              showsHorizontalScrollIndicator={false}
              scrollEnabled={false}
            >
              <View style={{width: screenWidth}}>
                <Text style={styles.descp}>{bookInfo.description}</Text>
              </View>
              <View style={{width: screenWidth,padding: 15}}>
                <View style={{justifyContent: 'space-between', flexDirection: 'row' }}>
                  <Text style={styles.catalogTitle}>共{cataLogsList.length}章</Text>
                  <TouchableWithoutFeedback onPress={this.handleClickSort}>
                    <View>
                      <Text style={{color: '#b79476', fontSize: 10}}>{btnText}</Text>
                    </View>
                  </TouchableWithoutFeedback>
                </View>
                  {
                    cataLogsList.map((item, i) =>
                      <TouchableWithoutFeedback key={i} onPress={() => {this.handleClickStartRead(item.contentKey)}}>
                        <View>
                          <Text style={styles.catalogItem}>{item.title}</Text>
                        </View>
                      </TouchableWithoutFeedback>
                    )
                  }
              </View>
            </ScrollView>
          </View>
        </ScrollView>
        <TouchableWithoutFeedback onPress={this.handleClickStartRead}>
          <View>
            <Text style={styles.startRead}>开始阅读</Text>
          </View>
        </TouchableWithoutFeedback>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  bookInfo: {
    flex: 1,
    backgroundColor: '#fff'
  },
  bookInfoTitle: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    paddingLeft: 20,
    paddingRight: 20,
    paddingTop: 15
  },
  bookCover: {
    width: 100,
    height: 140,
    marginRight: 20
  },
  bookTitle: {
    color: '#333',
    fontSize: 14
  },
  bookAuthor: {
    color: '#48878e',
    fontSize: 10,
    marginTop: 10,
    marginBottom: 10
  },
  readTime: {
    color: '#b3b3b3',
    fontSize: 10
  },
  backButtonContainer: {
    marginBottom: 20,
    borderStyle: 'solid',
    borderBottomWidth: 1,
    borderColor: '#eee',
    marginBottom: 3,
    paddingLeft: 15,
    paddingRight: 15
  },
  backButton: {
    paddingTop: 10,
    paddingBottom: 10,
    fontSize: 12
  },
  bookInfoContent: {
    marginTop: 30
  },
  bookInfoCTitle: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderStyle: 'solid',
    borderBottomWidth: 1,
    borderColor: '#eee'
  },
  bookInfoCTItemContainer: {
    width: screenWidth / 2,
    justifyContent: 'center',
    alignItems: 'center'
  },
  bookInfoCTItem: {
    width: 60,
    height: 40,
    lineHeight: 40,
    textAlign: 'center',
    fontSize: 12
  },
  itemActive: {
    color: '#333',
    borderBottomWidth: 2,
    borderBottomColor: '#333',
    borderStyle: 'solid'
  },
  descp: {
    marginTop: 10,
    paddingLeft: 15,
    paddingRight: 15,
    paddingBottom: 20,
    color: '#2b2b2b',
    fontSize: 12,
    lineHeight: 16
  },
  startRead: {
    height: 40,
    lineHeight: 40,
    backgroundColor: '#b79476',
    color: '#fff',
    textAlign: 'center'
  },
  catalogTitle: {
    fontSize: 10
  },
  catalogItem: {
    fontSize: 12,
    color: '#333',
    height: 36,
    lineHeight: 36,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    borderStyle: 'solid'
  }
})